package com.wuzf.navigation_test.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Menu;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.google.android.material.bottomnavigation.BottomNavigationItemView;
import com.google.android.material.bottomnavigation.BottomNavigationMenuView;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.bottomnavigation.LabelVisibilityMode;
import com.wuzf.navigation_test.R;
import com.wuzf.navigation_test.model.BottomBar;
import com.wuzf.navigation_test.model.Destination;

import java.util.Map;

public class BottomBarConfig extends BottomNavigationView {

    private static final int[] icons = new int[]{
            R.drawable.icon_tab_home,
            R.drawable.icon_tab_sofa,
            R.drawable.icon_tab_publish,
            R.drawable.icon_tab_movie,
            R.drawable.icon_tab_mine
    };
    private static final String BOTTOM_FILE_NAME = "main_tabs_config.json";

    private static BottomBar bottomBar = null;

    public BottomBarConfig(@NonNull Context context) {
        this(context, null);
    }

    public BottomBarConfig(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    @SuppressLint("RestrictedApi")
    public BottomBarConfig(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        BottomBar bottomBar = builderBottom();
        int[][] states = new int[2][];
        states[0] = new int[]{android.R.attr.state_selected};
        states[1] = new int[]{};

        int[] colors = new int[]{
                Color.parseColor(bottomBar.getActiveColor()),
                Color.parseColor(bottomBar.getInActiveColor())
        };
        ColorStateList stateList = new ColorStateList(states, colors);
        // 设置底部图标列表
        setItemIconTintList(stateList);
        // 设置字体颜色
        setItemTextColor(stateList);
        // 底部显示模式
        setLabelVisibilityMode(LabelVisibilityMode.LABEL_VISIBILITY_LABELED);
        // 默认选中的item
        setSelectedItemId(bottomBar.getSelectTab());

        for (BottomBar.Tabs tab : bottomBar.getTabs()) {
            if (!tab.isEnable()) {
                return;
            }
            int id = getItemId(tab.getPageUrl());
            if (id < 0) {
                return;
            }
            // groupId   itemId:navigate的id  order：序号   title：名称
            MenuItem menu = getMenu().add(0, id, tab.getIndex(), tab.getTitle());
            menu.setIcon(icons[tab.getIndex()]);

        }

        // 这里必须先把MenuItem设置完成之后，才能够进行bottom中元素的设置
        int index = 0;
        for (BottomBar.Tabs tab : bottomBar.getTabs()) {
            if (!tab.isEnable()) {
                return;
            }
            int id = getItemId(tab.getPageUrl());
            if (id < 0) {
                return;
            }

            // 设置icon图标的大小
            int size = dp2px(tab.getSize());

            // 得到第一个元素就是BottomNavigationMenuView
            BottomNavigationMenuView menuView = (BottomNavigationMenuView) this.getChildAt(0);
            BottomNavigationItemView itemView = (BottomNavigationItemView) menuView.getChildAt(index);
            itemView.setIconSize(size);
            if (TextUtils.isEmpty(tab.getTitle())) {
                String color = TextUtils.isEmpty(tab.getTintColor()) ? "#ff678f" : tab.getTintColor();
                itemView.setIconTintList(ColorStateList.valueOf(Color.parseColor(color)));
                itemView.setShifting(false);
            }
            index++;
        }

        // 设置底部导航栏默认选中项目
        if (bottomBar.getSelectTab() > 0 && bottomBar.getTabs().size() > bottomBar.getSelectTab()) {
            BottomBar.Tabs tabs = bottomBar.getTabs().get(bottomBar.getSelectTab());
            if (tabs.isEnable()) {
                int itemId = getItemId(tabs.getPageUrl());
                // 设置延迟加载
                post(() -> setSelectedItemId(itemId));
            }
        }
    }

    /**
     * 将dp转成px
     *
     * @param size
     * @return
     */
    private int dp2px(int size) {
        float rSize = getContext().getResources().getDisplayMetrics().density * size + 0.5f;
        return (int) rSize;
    }

    private int getItemId(String pageUrl) {
        Map<String, Destination> map = AppConfig.formatJson();
        if (map == null) {
            return -1;
        }
        return map.get(pageUrl).getId();
    }

    private BottomBar builderBottom() {
        if (bottomBar == null) {
            bottomBar = JSON.parseObject(AppConfig.parseJson(BOTTOM_FILE_NAME), BottomBar.class);
        }
        return bottomBar;
    }
}
